import React from 'react';
import $ from 'webpack-zepto';
import emptyImg from '../../../images/booking.png';
import Config from '../../common/config.js';
import Util from '../../common/util.js';
import Loader from '../../common/loader.js';
import Modal from '../../common/modal.js';


var scope;
export default class OrderList extends React.Component{

    constructor(props) {
        super(props);
        scope = this;
        scope.state = {
            orderList : [],
            page : 1,
            totalPage : 1
        };
        scope.getOrderList(scope.props.data);
    };

    next(){
        var page = scope.state.page;
        var totalPage = scope.state.totalPage;
        page += 1;
        if(page > totalPage){
            return;
        }
        scope.setState({
            page : page
        });

        scope.getOrderList(scope.props.data);
    };

    render(){
        return scope.state.orderList.length == 0 ? scope.empty() : scope.list();
    };

    getOrderList(type){
        var params = ['?uToken=' + Util.storage().get(scope.props.appId),'&p=' + scope.state.page];
        if('all' != type){
            params.push('&order_state=' + type);
        }

        var url = Config.path('duolu/order',params);
        $.ajax({
            url : url,
            type : 'get',
            dataType : 'json',
            beforeSend : function(){
                Loader.start();
            },
            success : function(resp){
                if(resp.status == 200){
                    scope.setState({
                        orderList : scope.state.orderList.concat(resp.data.list),
                        totalPage : resp.data.page.totalPage
                    });
                }else if(resp.status == 401){
                    window.location.href = 'index.html?appid=' + Util.getUrlParam('appid');
                }
                Loader.end();
            }
        });
    };

    //when props having changed
    componentWillReceiveProps(props){
        scope.setState({
            page : 1,
            totalPage : 1,
            orderList : []
        });
        scope.getOrderList(props.data);
    };

    empty(){
        return (
            <div className="content">
                <div className="empty">
                    <img src={emptyImg}></img>
                    <p>没有该类型订单!</p>
                </div>
            </div>
        );
    };

    list(){
        var items = scope.state.orderList.map(function(order,i){
            return (
                <div className="order" key={i}>
                    {scope.orderHeader(order)}
                    {scope.goodsInfo(order.goods)}
                    {scope.orderFooter(order)}
                </div>
            );
        });

        return (
            <div className="list">
                {items}
                {scope.pageBtn()}
            </div>
        );
    };

    pageBtn(){
        if(scope.state.page >= scope.state.totalPage){
            return;
        }

        return (
            <div className="pageBtn" onClick={scope.next}>加载更多</div>
        );
    };

    goodsInfo(list){
        return list.map(function(goods,i){
            return (
                <div className="goods" onClick={scope.go.bind(this,function(){
                    window.location.href = 'goods-view.html?goods_common_id=' + goods.gc_id + '&appid=' + Util.getUrlParam('appid');
                })} key={i}>
                    <div className="goods-left">
                        <div className="img">
                            <img src={goods.goods_thumb}></img>
                        </div>
                        <div className="goods-info">
                            <div className="name">
                                {goods.gc_name}
                                {scope.isActivityGoods(goods.act_name)}
                            </div>
                            <div className="spec">
                                规格 : <label>{goods.spec_desc}</label>
                            </div>
                        </div>
                    </div>
                    <div className="goods-right">
                        <div className="price">
                            RMB <label>{goods.sale_price}</label>
                        </div>
                        <div className="amount">
                            X {goods.goods_num}
                        </div>
                    </div>
                </div>
            );
        });
    };

    isActivityGoods(actName){
        return actName ? <img src="images/chaozhigou.png" alt="超值购icon"/> : '';
    };

    orderFooter(order){
        var total = 0;
        order.goods.map(function(goods){
            total += goods.sale_price * goods.goods_num;
        });
        return (
            <div className="mod">
                <div className={'total-price ' + (order.state == '待付款' ? '' : 'no-border')}>总金额 : RMB <label>{total}</label></div>
                {order.state == '待付款' || order.state == '已完成' ? scope.orderMod(order) : ''}
            </div>
        );
    };

    go(callback){
        callback.call();
    };

    orderMod(order){
        let text = '取消';
        if(order.order_state != '10'){
            text = '删除'
        }
        return (
            <div>
                <a className="cancel" onClick={scope.cancelOrder.bind(this,order)}>{text}订单</a>
                {order.state == '待付款' ? <a className="pay" onClick={scope.payOrder.bind(this,order)}>立即支付</a> : ''}
            </div>
        );
    };

    orderHeader(order){
        return (
            <div className="list-header" onClick={scope.go.bind(this,function(){
                   Util.storage().put('orderDetail',order);
                   window.location.href = 'order.html?type=detail&appid=' + Util.getUrlParam('appid');
            })}>
                <span>订单编号 : <label>{order.order_sn}</label></span>
                <span>下单时间 : <label>{order.create_time}</label></span>
                <span>{order.state}</span>
            </div>
        );
    };



    cancelOrder(order){
        Modal.modal({
            isSuccess : false,
            header : '提示!',
            body : '确认取消该订单?',
            firstBtn : {
                text : '取消'
            },
            secondBtn : {
                text : '确定',
                isCallback : function(){
                    $.ajax({
                        url : Config.path('duolu/order',['?uToken=' + Util.storage().get(scope.props.appId) , '&oid=' + order.oid]),
                        type : 'delete',
                        beforeSend : function(){
                            Loader.start();
                        },
                        success : function(resp){
                            if(resp.status == 200){
                                window.location.reload();
                            }else if(resp.status == 401){
                                window.location.href = 'index.html?appid=' + Util.getUrlParam('appid');
                            }
                            Loader.end();
                        }
                    });
                }
            },
            lowerBody : false
        });
    };

    payOrder(order){
        let yhg_goods = [];
        let goodsList = [];
        let totalPrice = 0;
        for(let i in order.goods){
            let goods = order.goods[i];
            if(goods.act_name && goods.act_name != ''){
                goods.gc_thumb = goods.goods_thumb;
                goods.add_price = goods.sale_price;
                goods.yhg_goods_num = goods.goods_num;
                yhg_goods.push(goods);
            }else{
                goodsList.push(goods);
            }
        }

        for(let i in goodsList){
            let goods = goodsList[i];
            goods.yhg_goods = [];
            for(let i in yhg_goods){
                let yhgGoods = yhg_goods[i];
                if(yhgGoods.goods_pid == goods.goods_id){
                    goods.yhg_goods.push(yhgGoods);
                    totalPrice += parseInt(yhgGoods.sale_price) * yhgGoods.goods_num;
                }
            }
            totalPrice += parseInt(goods.sale_price) * goods.goods_num;
        }

        let data = {
            orderGoods : goodsList,
            totalPrice : totalPrice,
            oid : order.oid
        };
        Util.storage().put('toBuyGoods',data);
        location.href = 'order.html?type=buy&appid=' + Util.getUrlParam('appid');
    };
};